﻿
using System.Collections.Generic;
using Unity.Netcode;
using UnityEngine;

public class NGOPool<T> : INetworkPrefabInstanceHandler where T : Component
{
    private  GameObject prefab;
    private  Queue<T> pool = new();    
    private int maxNum;

    public NGOPool(GameObject prefab, int maxNum = 10)
    {
        this.prefab = prefab;        
        this.maxNum = maxNum;     
    }

    private T CreateInstance()
    {        
        T obj=GameObject.Instantiate(prefab).GetComponent<T>();        
        return obj;
    }    

    public NetworkObject Instantiate(ulong ownerClientId, Vector3 position, Quaternion rotation)
    {
        NetworkObject obj;
        if (pool.Count > 0)
        {            
            obj= pool.Dequeue().GetComponent<NetworkObject>();
            obj.gameObject.SetActive(true);
        }
        else
        {
            obj = CreateInstance().GetComponent<NetworkObject>();
        }
        obj.transform.SetPositionAndRotation(position, rotation);
        return obj;
    }

    public void Destroy(NetworkObject networkObject)
    {
        if(pool.Count >=maxNum)
        {
            GameObject.Destroy(networkObject.gameObject);            
        }
        else
        {
            pool.Enqueue(networkObject.GetComponent<T>());
            networkObject.gameObject.SetActive(false);
        }
    }
}